/*
 * @Author: xiaoliang
 * @Date: 2025-03-05 14:47:12
 * @LastEditors: xiaoliang
 * @LastEditTime: 2025-03-05 14:47:13
 * @FilePath: /codepiece/sendrequest.js
 * @Description: 并发控制
 */

function sendRequest(requests, max) {
  let i = 0;
  const results = [];
  const executing = [];

  const enqueue = () => {
    if (i === requests.length) {
      return Promise.resolve();
    }
    const request = requests[i++].then(res => {
      results.push(res);
      return res;
    });
    executing.push(request);
    request.finally(() => executing.splice(executing.indexOf(request), 1));
    let r = Promise.resolve();
    if (executing.length >= max) {
      r = Promise.race(executing);
    }
    return r.then(() => enqueue());
  };

  return enqueue().then(() => results);
}

// 假设 `requests` 是一个包含10个请求的 Promise 数组
sendRequest(requests, 3).then(results => {
  console.log(results);
});